package com.chinaedu.oc.action.productline;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chinaedu.oc.bo.ProductLineQuery;
import com.chinaedu.oc.constant.Constant;
import com.chinaedu.oc.context.Common.Session;
import com.chinaedu.oc.entity.common.CodeList;
import com.chinaedu.oc.entity.manageuser.ManageUser;
import com.chinaedu.oc.po.dto.PubOutputDto;
import com.chinaedu.oc.po.productline.ProductLine;
import com.chinaedu.oc.po.productline.ProductLineDepartment;
import com.chinaedu.oc.po.productline.ProductLineKey;
import com.chinaedu.oc.po.productline.dto.AddProductLineInput;
import com.chinaedu.oc.po.productline.dto.AddProductLineOutput;
import com.chinaedu.oc.po.productline.dto.ConfigProductLineKeyInput;
import com.chinaedu.oc.po.productline.dto.ConfigProductLineKeyOutput;
import com.chinaedu.oc.po.productline.dto.CreateProductLineKeyOutput;
import com.chinaedu.oc.po.productline.dto.QueryProductLineInput;
import com.chinaedu.oc.po.productline.dto.QueryProductLineOutput;
import com.chinaedu.oc.po.productline.dto.StartUseProductLineInput;
import com.chinaedu.oc.service.cache.ProductLineCacheServ;
import com.chinaedu.oc.service.cache.StaticCacheServ;
import com.chinaedu.oc.uri.IName;
import com.chinaedu.oc.util.common.JsonUtil;
import com.chinaedu.oc.util.common.StringUtil;
import com.chinaedu.oc.util.csv.CsvCreater;
import com.chinaedu.oc.util.http.HttpHelper;
import com.chinaedu.oc.util.http.HttpRequestException;
import com.chinaedu.oc.vo.CommonListVo;
import com.chinaedu.oc.vo.QueryProductLine;

import ch.qos.logback.core.Context;

@Controller
@RequestMapping("/productline")
public class ProductLineAction {
	
	@Autowired
	StaticCacheServ cacheServ;
	@Autowired
	ProductLineCacheServ productLineCacheServ;	
	
	/**
	 * @throws HttpRequestException 
	 * 添加产品线
	 * @Description: TODO
	 * @param     
	 * @return void    返回类型 
	 * @throws
	 */
	@RequestMapping("/add")
	@ResponseBody
	public AddProductLineOutput addProductLine(ProductLine productLine, HttpServletRequest response, HttpServletRequest request) throws HttpRequestException {
		String[] department = request.getParameterValues("departmentId[]");
		
		//组建参数
		AddProductLineInput input = new AddProductLineInput();
		input.setProductLine(productLine);
		List<ProductLineDepartment> list = new ArrayList<ProductLineDepartment>();
		if(department != null) {
			for(String s : department) {
				ProductLineDepartment p = new ProductLineDepartment();
				p.setDepartmentId(s);
				
				list.add(p);
			}
		}
		input.setProductLineDepartmentList(list);
		ManageUser userLogin= (ManageUser) request.getSession().getAttribute(Session.manageUserLogin.name());
		input.setUser(userLogin.getUserId());
		
		AddProductLineOutput out = new AddProductLineOutput();
		out = HttpHelper.sendRequest(IName.ProductLine.ADD_UPDATE_PRODUCT_LINE, input, AddProductLineOutput.class);
		
		if(Constant.TRUE == out.getStatus()) {
			productLineCacheServ.addCache();
		}
		
		return out;
		
	}
	
	/**
	 * @return 
	 * @throws HttpRequestException 
	 * 查询
	 * @Description: TODO
	 * @param @param response    
	 * @return void    返回类型 
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/query")
	@ResponseBody
	public CommonListVo<QueryProductLine> queryProductLine(ProductLineQuery productLineQuery, Integer start, Integer length) throws HttpRequestException {
		
		
		QueryProductLineInput input = new QueryProductLineInput();
		input.setProductLineQuery(productLineQuery);
		input.setStart(start);
		input.setLength(length);
		
		
		CommonListVo<QueryProductLine> outVo = new CommonListVo<QueryProductLine>();
		
		
		
		//加f_
		if(input.getProductLineQuery() != null) {
			String orderName  = input.getProductLineQuery().getOrderName();
			if(!StringUtil.isBlack(orderName)) {
				orderName = StringUtil.underscoreName(orderName);
				input.getProductLineQuery().setOrderName("f_"+orderName);
			}
		}
		
		//全部转null
		if(Constant.QUERY_ALL.equals(productLineQuery.getBusinessType())) {
			productLineQuery.setBusinessType(null);
		}
		if(Constant.QUERY_ALL.equals(productLineQuery.getStartUse())) {
			productLineQuery.setStartUse(null);
		}
		
		//第一次走缓存
		if(com.chinaedu.oc.context.Context.isCacheProductLine) {
			productLineCacheServ.addCache();
			com.chinaedu.oc.context.Context.isCacheProductLine = false;
		}
		
		//查询
		QueryProductLineOutput out = HttpHelper.sendRequest(IName.ProductLine.QUERY_PRODUCT_LINE, input, QueryProductLineOutput.class);
		
		if(Constant.FALSE ==  out.getStatus()) {
			outVo.setStatus(out.getStatus());
			outVo.setMsg(out.getMsg());
			
			return outVo;
		}
		
		List<ProductLine> list = out.getDataList();
		//组装数据
		List<QueryProductLine> listVo = new ArrayList<QueryProductLine>();
		for(ProductLine p : list) {
			QueryProductLine vo = JsonUtil.toBean(JsonUtil.toJson(p), QueryProductLine.class);
			vo.setBusinessId(new String[] {p.getBusinessType()});
			vo.setBusinessName(new String[] {cacheServ.queryData("business_type", p.getBusinessType(), CodeList.class).getValue()});
			
			
			List<ProductLineDepartment> listD = out.getProductLineDepartmentList().get(p.getId());
			if(listD != null && list.size()>=1) {
				String[] ids = new String[listD.size()];
				String[] names = new String[listD.size()];
				
				for(int i=0; i<listD.size(); i++) {
					ids[i] = listD.get(i).getDepartmentId();
					names[i] = cacheServ.queryData("department", ids[i], CodeList.class).getValue();
				}
				
				vo.setDepartmentId(ids);
				vo.setDepartmentName(names);
			}
			
			listVo.add(vo);
		}
		
		outVo.setRecordsFiltered(out.getTotals()+"");
		outVo.setRecordsTotal(outVo.getRecordsFiltered());
		outVo.setData(listVo);
		outVo.setStatus(Constant.TRUE);
		
		return outVo;
		
	}
	
	/**
	 * @return 
	 * @throws HttpRequestException 
	 * 配置
	 * @Description: TODO
	 * @param @param input    
	 * @return void    返回类型 
	 * @throws
	 */
	@RequestMapping("/config")
	@ResponseBody
	public PubOutputDto configProductLine(ProductLineKey productLineKey) throws HttpRequestException {
		ConfigProductLineKeyInput input = new ConfigProductLineKeyInput();
		input.setProductLineKey(productLineKey);
		return HttpHelper.sendRequest(IName.ProductLine.CONFIG_PRODUCT_LINE, input, PubOutputDto.class);
	}
	/**
	 * 查询秘钥
	 * @Description: TODO
	 * @param @param productLineKey
	 * @param @return
	 * @param @throws HttpRequestException    
	 * @return ProductLineKey    返回类型 
	 * @throws
	 */
	@RequestMapping("/queryKey")
	@ResponseBody
	public ConfigProductLineKeyOutput queryKey(String id) throws HttpRequestException {
		ConfigProductLineKeyInput input = new ConfigProductLineKeyInput();
		ProductLineKey productLineKey = new ProductLineKey();
		productLineKey.setProductLine(id);
		input.setProductLineKey(productLineKey);
		ConfigProductLineKeyOutput out = HttpHelper.sendRequest(IName.ProductLine.QUERY_PRODUCT_LINE_KEY, input, ConfigProductLineKeyOutput.class);
		return out;
	}
	
	
	/**
	 * @throws HttpRequestException 
	 * @return 
	 * 生成秘钥
	 * @Description: TODO
	 * @param     
	 * @return void    返回类型 
	 * @throws
	 */
	@RequestMapping("/createKey")
	@ResponseBody
	public CreateProductLineKeyOutput createKey() throws HttpRequestException {
		CreateProductLineKeyOutput out = new CreateProductLineKeyOutput();
		out = HttpHelper.sendRequest(IName.ProductLine.CREATE_PRODUCT_LINE_KEY, null, CreateProductLineKeyOutput.class);
		return out;
	}
	
	/**
	 * 启用停用
	 * @Description: TODO
	 * @param @param input
	 * @param @return
	 * @param @throws HttpRequestException    
	 * @return PubOutputDto    返回类型 
	 * @throws
	 */
	@RequestMapping("/startUse")
	@ResponseBody
	public PubOutputDto startUse(StartUseProductLineInput input) throws HttpRequestException {
		PubOutputDto out = HttpHelper.sendRequest(IName.ProductLine.START_STOP_USE_PRODUCT_LINE, input, PubOutputDto.class);
		return out;
	}
	/**
	 * @throws HttpRequestException 
	 * 导出
	 * @Description: TODO
	 * @param @param input    
	 * @return void    返回类型 
	 * @throws
	 */
	
	public void export(ProductLineQuery productLineQuery, Integer start, Integer length, HttpServletResponse response) throws HttpRequestException {
		
		CommonListVo<QueryProductLine> queryProductLine = this.queryProductLine(productLineQuery, start, length);
		List<QueryProductLine> list = queryProductLine.getData();
		CsvCreater<QueryProductLine> cc = new CsvCreater<QueryProductLine>();
		cc.createCsv(list, 
				new String[] {"code", "name", "portalAddress", "header", "businessName","departmentName", "comments"},
				new String[] {"编码", "名称", "网址", "负责人", "业务类型", "部门", "备注"} , 
				"产品线导出", 
				response);
	}
	
}
